"use strict";
import jsPDF from "jspdf";
import html2canvas from "html2canvas";

export default async (html, title) => {
  let contentWidth = html.clientWidth; // 获得该容器的宽
  let contentHeight = html.clientHeight; // 获得该容器的高
  let canvas = document.createElement("canvas");
  let scale = 1; // 解决清晰度问题，先放大 2倍

  canvas.width = contentWidth * scale; // 将画布宽&&高放大两倍
  canvas.height = contentHeight * scale;
  canvas.getContext("2d").scale(scale, scale);

  let opts = {
    scale: scale,
    canvas: canvas,
    width: contentWidth,
    height: contentHeight,
    useCORS: true,
  };

  return html2canvas(html, opts).then((canvas) => {
    console.log("html", html, "opts", opts);
    let pageData = canvas.toDataURL("image/jpeg", 1.0); // 清晰度 0 - 1
    let pdf;
    //一页 pdf 显示 html 页面生成的 canvas高度
    let pageHeight = (contentWidth / 552.28) * 841.89;
    //未生成 pdf 的 html页面高度
    let leftHeight = contentHeight;
    //页面偏移
    let position = 0;
    //a4纸的尺寸[595.28,841.89]，html 页面生成的 canvas 在pdf中图片的宽高
    let imgWidth = 555.28;
    let imgHeight = (imgWidth / contentWidth) * contentHeight;
    pdf = new jsPDF("", "pt", "a4"); // 下载尺寸 a4 纸 比例
    //有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
    //当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(pageData, "JPEG", 20, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        pdf.addImage(pageData, "JPEG", 20, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= 841.89;
        //避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    pdf.save(title);
  });
};
